package com.yupi.yupicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.space.SpaceUpdateRequest;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.service.SpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/space")
public class SpaceController {
    @Autowired
    private SpaceService spaceService;

    /**
     * 更新空间信息
     *
     * @param spaceUpdateRequest 空间更新请求参数
     * @return 是否更新成功
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        // 参数校验：请求参数不能为空且id必须大于0
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将请求参数转换为Space实体对象
        Space space = new Space();
        BeanUtil.copyProperties(spaceUpdateRequest, space);
        // 根据空间级别填充默认配置（如最大容量、最大数量等）
        spaceService.fillSpaceBySpaceLevel(space);
        // 校验空间参数是否合法
        spaceService.validSpace(space, false);
        // 获取要更新的空间原始数据
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        // 如果原始空间不存在，抛出异常
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 执行更新操作
        boolean result = spaceService.updateById(space);
        // 如果更新失败，抛出异常
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回更新成功的结果
        return ResultUtils.success(true);
    }
}
